package top.abilities.util.base;


import com.fasterxml.jackson.core.JsonProcessingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import top.abilities.util.util.Jsons;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 控制器基类
 */
public abstract class BaseJsonController {

    private final static Logger _log = LoggerFactory.getLogger(BaseJsonController.class);

    @ExceptionHandler
    public void exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception exception){
        _log.info("统一异常处理：", exception);
        _log.info("访问路径：{}",request.getRequestURL());
        try {
            _log.info("访问参数：{}", Jsons.objToJson(request.getParameterMap()));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        request.setAttribute("ex", exception);
        if (null != request.getHeader("X-Requested-With") && request.getHeader("X-Requested-With").equalsIgnoreCase("XMLHttpRequest")) {
            request.setAttribute("requestHeader", "ajax");
        }
        response.setContentType("application/json;charset=UTF-8");
        try {
            BaseResult baseResult=new BaseResult(-1,"faild",exception.getMessage());
            response.getWriter().write(Jsons.objToJson(baseResult));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /*public static String jsp(String path) {
        return path.concat(".jsp");
    }

    *//**
     * 返回thymeleaf视图
     * @param path
     * @return
     *//*
    public static String thymeleaf(String path) {
        String folder = PropertiesFileUtil.getInstance().get("app.name");
        return "/".concat(folder).concat(path).concat(".html");
    }*/
}
